package dyyx.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import dyyx.dto.HostInfo;

public abstract class HostInfoUtil {

    private static HostInfo     hostInfo = null;
    private static final String IP127    = "127.0.0.1";

    public static final String  TYPE1    = "1";
    public static final String  TYPE2    = "2";

    private static String       error1   = null;
    private static String       error2   = null;

    static {
        HostInfo hitmp = fetchHostInfo();
        if (hitmp != null) {
            hostInfo = hitmp;
        }
    }

    public static HostInfo getHostInfo() {
        return hostInfo;
    }

    private static HostInfo fetchHostInfo() {
        // getHostAddress()
        InetAddress ia = null;

        try {

            ia = InetAddress.getLocalHost();
            String hostname = null;
            String hostip = null;
            if (ia != null) {
                hostname = ia.getHostName();
                hostip = ia.getHostAddress();
                if (CommUtil.isNotBlank(hostip) && !IP127.equals(hostip)) {
                    HostInfo hi = new HostInfo();
                    hi.setIp(hostip);
                    hi.setName(hostname);
                    hi.setType(TYPE1);
                    return hi;
                }
            }

        } catch (Throwable e) {
            error1 = e + "";
        }

        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                        && inetAddress.isSiteLocalAddress()) {
                        HostInfo hi = new HostInfo();
                        hi.setIp(inetAddress.getHostAddress());
                        hi.setName(inetAddress.getHostName());
                        hi.setType(TYPE2);
                        return hi;
                    }

                }
            }

        } catch (Throwable e) {
            error2 = e + "";
        }

        return null;
    }

    public static String getHostIp() {
        if (hostInfo == null) {
            return "host-" + System.currentTimeMillis();
        }
        return hostInfo.getIp();
    }

}
